<?php 
namespace Qwadmin\Controller;

class KuController extends ComController
{
	// private $stock = M('stock');


	//库存展示
	public function index()
	{

		$db = M("stock");
        // $where = "a_id=".$uid;
        $count = $db->count();
        $pagecount = 20;
        $page = new \Think\Page($count , $pagecount);
        // $row[] = '';
        $page->parameter = $row; //此处的row是数组，为了传递查询条件
        $page->setConfig('first');
        $page->setConfig('prev','上一页');
        $page->setConfig('next','下一页');
        $page->setConfig('last','尾页');
        $page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% 第 '.I('p',1).' 页/共 %TOTAL_PAGE% 页 ( '.$pagecount.' 条/页 共 %TOTAL_ROW% 条)');
        $show = $page->show();
        $list = $db->order('time desc')->limit($page->firstRow.','.$page->listRows)->select();
        $this->assign('list',$list);
        $this->assign('page',$show);



		$this->display();
	}




	//库存添加
	public function add()
	{
		
		$stock = M('stock');
		if (IS_POST) {
			
			// dump($_POST);
			// dump($_FILES);
			// exit;
			$arr = $_POST;

			$dada = $stock->select();

			if ($arr['name'] == $dada[0]['name']) {
				$this->success('此物品已在库存中,无需重新添加;');
				exit;
			}

			$upload = new \Think\Upload();// 实例化上传类
	        $upload->maxSize = 3145728 ;// 设置附件上传大小
	        $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
	        $upload->rootPath = './Public/Uploads/'; // 设置附件上传根目录
	        $upload->savePath = ''; // 设置附件上传（子）目录
	        // 上传文件
	        $info = $upload->upload();
			// dump($info);
			// exit;
			$idata = $info['photo']['savepath'].$info['photo']['savename'];
	       	// 缩略图片打开地址拼接
	        $imgname = "/Uploads/".$idata;
	        // echo $imgname;
	        // exit;
	        $arr['img'] = $imgname;
	        $arr['time'] = date('Y-m-d');
	        if ($stock->add($arr) > 0) {
	        	$this->success('添加成功');
	        	exit;
	        }else{
	        	$this->error('添加失败,请重新填写;');
	        	exit;
	        }
			
		}else{
				$db = M("stock");
				// $apost = $glist[0]['post'];
				// $x_list = M('look')->where(['look'=>0,'ment'=>$apost,'ju'=>0,'type'=>0])->order('id DESC')->select();
				$count = $db->count();
				// dump($count);
				// exit;
				$pagecount = 20;
				$page = new \Think\Page($count , $pagecount);
				// $row[] = '';
				$page->parameter = $row; //此处的row是数组，为了传递查询条件
				$page->setConfig('first');
				$page->setConfig('prev','上一页');
				$page->setConfig('next','下一页');
				$page->setConfig('last','尾页');
				$page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% 第 '.I('p',1).' 页/共 %TOTAL_PAGE% 页 ( '.$pagecount.' 条/页 共 %TOTAL_ROW% 条)');
				$show = $page->show();
				$list = $db->order('x_type ASC')->limit($page->firstRow.','.$page->listRows)->select();
				$this->assign('list',$list);
				$this->assign('page',$show);
				$this->display();

		}
			
	}

	//固定资产添加
	public function addto()
	{

		switch ($_POST['type']) {
			case '1':
				$stock = M('stock');
				$name = $_POST['name'];
				$number = $_POST['number'];


				$list = $stock->where(array('name'=>$name))->select();

				$number = $list[0]['number']+$number;

				// echo $number;
				
				$id = $list[0]['id'];
				if ($stock->where(array('id'=>$id))->save(array('number'=>$number)) >=0) {
					echo '1111';
				}else{
					echo '2222';
				}
				break;




			case '2':
				// dump($_POST);
				$list = $_POST;
				$list['time'] = date('Y-m-d');
				$ulist = M('member')->where(array('user'=>$_POST['uname']))->select();
				$u_id = $ulist[0]['uid'];
				$gid = M('auth_group_access')->where(array('uid'=>$u_id))->select();
				$g_id = $gid[0]['group_id'];
				$glist = M('auth_group')->where(array('id'=>$g_id))->select();
				$gname = $glist[0]['title'];
				// echo $gname;
				// 
				$list['ment'] = $gname;

				if (M('fixed')->add($list) > 0) {
					echo '1111';
				}else{
					echo '2222';
				}

				break;
			
		}




		// dump($_POST);
		// exit;
		// $stock = M('stock');
		// $name = $_POST['name'];
		// $number = $_POST['number'];


		// $list = $stock->where(array('name'=>$name))->select();

		// $number = $list[0]['number']+$number;

		// // echo $number;
		
		// $id = $list[0]['id'];
		// if ($stock->where(array('id'=>$id))->save(array('number'=>$number)) >=0) {
		// 	echo '1111';
		// }else{
		// 	echo '2222';
		// }





	}

	//物资名搜索
    public function sou()
    {
          // dump(I());
          $list = $_POST;
          $wname = $list['wname'];
          // dump($list);
          // exit;
    
          // $data['name']= array('like','%'.$wname.'%');
          $cname['name']= array('like','%'.$wname.'%');
          // $data['x_type'] = $list['x_type'];
          if (empty($wname)) {
            echo '1111';
            exit;
          }
          $wlist = M('stock')->where($cname)->select();
          if (!empty($wlist)) {
             // $arr = M('stock')->where($data)->select();
              $this->ajaxReturn($wlist);
          }else{
            echo '2222';
          }
     
        
        







    }






	public function xiu()
	{
		// dump(I());
		// exit;
		$id = $_POST['id'];
		$list['unit'] = $_POST['unit'];
		$list['number'] = $_POST['number'];
		if (M('stock')->where(['id'=>$id])->save($list) > 0) {
			echo '111';
			
		}else{
			echo '222';
		}
		
	}






    public function del()
    {

    	// dump(I());
    	// exit;
    	$id = $_POST['id'];
    	if (M('stock')->where(['id'=>$id])->delete() > 0) {
    		echo '1111';
    	}else{
    		echo '2222';
    	}

        // $ids = isset($_REQUEST['ids']) ? $_REQUEST['ids'] : false;

        // // dump($ids);
        // // exit;
        // //uid为1的禁止删除
        // // if ($ids == 1 or !$ids) {
        // //     $this->error('参数错误！');
        // // }
        // if (is_array($ids)) {
        //     foreach ($ids as $k => $v) {
        //         if ($v == 1) {//uid为1的禁止删除
        //             unset($ids[$k]);
        //         }
        //         $ids[$k] = intval($v);
        //     }


        //     if (!$ids) {
        //         $this->error('参数错误！');
        //         $ids = implode(',', $ids);
                
        //     }
        // }

        // $map['id'] = array('in', $ids);
        // if (M('stock')->where($map)->delete()) {
        //     // M('auth_group_access')->where($map)->delete();
        //     addlog('已删除:' . $ids);
        //     $this->success('恭喜，删除成功！');
        // } else {
        //     $this->error('参数错误！');
        // }
    }




    public function eadd()
	{
			// dump($_FILES ['file_stu'] ['name']);
			// exit;

		$model=M("stock");
		if (! empty ( $_FILES ['file'] ['name']))
		{
			$tmp_file = $_FILES ['file'] ['tmp_name'];
			
			$file_types = explode (".",$_FILES ['file'] ['name'] );
			$file_type = $file_types[count( $file_types)-1];
			if (strtolower( $file_type ) !== "xls" && strtolower( $file_type ) !== "xlsx" && strtolower( $file_type ) !== "csv"){
				echo "<script>alert('不是Excel文件，重新上传');window.location.href='".__APP__."/Ku/add'</script>";
				
			}
			$savePath = './Public/upfile/Excel';

			$str = date ( 'Ymdhis' );
			$file_name = $str . "." . $file_type;

			if (! copy ($tmp_file, $savePath.$file_name)){
				echo("failed");
			}else{
				$excelpath=$savePath . $file_name;

				$tableCols = array(
					'name','number','com','unit', 'time','zong','x_type'
				);
				//获取表格数据
				$data=importExcel($excelpath);
				//处理数据为空的数组
				foreach ($data as $k => $v ){
		           foreach ($v as $key => $value){
		               if (!$value){
		                   unset($data[$k][$key]);
		                   continue;
		               }
		           }
		           // if(empty($v)){
		           //     unset($list[$k]);
		           // }
		        }
          		$result = array_filter($data);
				// dump($result);
				// exit;
				M()->startTrans();
				foreach ($result as $k => $va) {
					$list['name'] = $va[1];
					$list['gui'] = $va[2];
					$list['com'] = $va[3];
					$list['unit'] = $va[4];
					$list['number'] = $va[5];
					$list['zong'] = $va[6];
					switch ($va[0]) {
						case '办公用品':
							$list['x_type'] = '1';
							break;
						case '劳保用品':
							$list['x_type'] = '2';
							break;
						case '招待用品':
							$list['x_type'] = '3';
							break;
					}
					
					$list['time'] = date('Y-m-d');
					if (!M('stock')->add($list)) {
                        M()->rollback();
                        return $this->error('添加失败');
                    }
				}
				M()->commit();
				return $this->success('添加成功');;
				// exit;
				// dump($arr);
				// exit;
					// 	M()->startTrans();
     //                    foreach ($result as $value) {
     //                        $value['time'] = date('Y-m-d');  //添加时间
     //                        $value['ment'] = $m_list[0]['post']; //部门
     //                        // $value['type'] = 2;
     //                        $value['uname'] = $dada[0]['user']; //申请人
     //                        $value['look'] = 0;  //审批值
     //                        if (!M('cost')->add($value)) {
     //                            M()->rollback();
     //                            return $this->error('添加失败');
     //                        }
     //                    }
     //                    M()->commit();
     //                    return $this->success('添加成功');
					// if (M('stock')->addALL($arr) > 0 ) {
					// 	echo "<script>alert('导入成功');window.location.href='".__APP__."/Ku/add'</script>";
					// }else{
					// 	echo "<script>alert('导入失败');window.location.href='".__APP__."/Ku/add'</script>";
					// }
					
			
				
			}
		}else{
			echo "<script>alert('请上传文件');window.location.href='".__APP__."/Ku/add'</script>";
			
		}
	}






	public function addo()
	{
		if (IS_POST) {
	          $dada = M('member')->where(array('uid'=>$_SESSION['uid']))->select();
	          $z_id = M('auth_group_access')->where(array('uid'=>$_SESSION['uid']))->select();
	                  
	          $b_id = $z_id[0]['group_id'];
	          $m_list = M('auth_group')->where(array('id'=>$b_id))->select();
	          $slist = M('stock')->where(['id'=>$_POST['id']])->select();
	          $list = $_POST;
	          foreach ($list as $k => $v ){
	             foreach ($v as $key => $value){
	                 if (!$value){
	                     unset($list[$k][$key]);
	                     continue;
	                 }
	             }
	             // if(empty($v)){
	             //     unset($list[$k]);
	             // }
	            }
	          $result = array_filter($list);
	            
	          $result = array_values($result); 
	          foreach ($result as $key => $vv) {
	          		
	          		switch ($vv['x_type']) {
	          			case '办公用品':
	          				$vv['x_type'] = '1';
	          				
	          				break;
	          			case '劳保用品':
	          				$vv['x_type'] = '2';
	          				break;
	          			case '招待用品':
	          				$vv['x_type'] = '3';
	          				break;
	          		}

	          		// dump($vv);
	          		$arr[] = $vv;
	          }
	          // dump($arr);
	          // exit;
	          M()->startTrans();
	          foreach ($arr as $value) {
	              if (!M('stock')->add($value)) {
	                  M()->rollback();
	                  return $this->error('添加失败');
	              }
	          }
	          M()->commit();
	          return $this->success('添加成功');


	    }else{
	      $this->display();
	    }
	}









}